<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>图片懒加载示例</title>
    <style>
        /* 可以设置图片容器的样式等，这里简单设置下图片宽度等 */
        img {
            display: block;
            width: 300px;
            height: 700px;
        }
    </style>
</head>

<body>
    <img src="placeholder.jpg" data-src="https://img.36krcdn.com/20190905/v2_1567641293753_img_png" alt="图片1">
    <img src="placeholder.jpg" data-src="https://img.36krcdn.com/20190905/v2_1567641293753_img_png" alt="图片2">
    <img src="placeholder.jpg" data-src="https://img.36krcdn.com/20190905/v2_1567641293753_img_png" alt="图片3">
    
    <script>
        function lazyLoad() {
            const lazyImages = document.querySelectorAll('img');
            // // 获取文档的可视区高度
            const windowHeight = document.documentElement.clientHeight;
            const scrollTop = document.documentElement.scrollTop;

            lazyImages.forEach((img) => {
                const imgOffsetTop = img.offsetTop;//相对于其 offsetParent 元素的顶部内边距的距离。
                // 最近的父定位元素，如果没定位的话则为body
                if (imgOffsetTop < windowHeight + scrollTop) {
                    const src = img.dataset.src;
                    img.src = src;
                    img.classList.remove('lazyload');
                }
            });
        }

        // 初次加载页面时检查图片是否需要加载
        window.addEventListener('load', lazyLoad);
        // 滚动页面时也检查图片是否进入可视区域需要加载
        window.addEventListener('scroll', lazyLoad);
    </script>
</body>

</html>